package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.EduTeacher;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.enums.CourseStatus;
import com.atguigu.eduservice.entity.vo.CourseFrontVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.entity.vo.CourseWebVo;
import com.atguigu.eduservice.feign.VodFeign;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.*;
import com.atguigu.servicebase.exceptionhandler.ELeanExeception;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Panghl
 * @since 2021-01-06
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private EduCourseMapper eduCourseMapper;

    @Override
    public String add(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int row = baseMapper.insert(eduCourse);
        if (row <= 0) {
            //添加失败
            throw new ELeanExeception(20001, "添加课程信息失败");
        }

        //获取添加之后课程id
        String cid = eduCourse.getId();

        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo, eduCourseDescription);
        eduCourseDescription.setId(cid);
        //向简介表中添加描述信息
        if (eduCourseDescriptionService.save(eduCourseDescription)) {
            return cid;
        }
        return null;
    }

    /**
     * 根据id获取课程基本信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        EduCourse eduCourse = baseMapper.selectById(courseId);
        EduCourseDescription courseDesc = eduCourseDescriptionService.getById(courseId);
        if (eduCourse != null) {
            BeanUtils.copyProperties(eduCourse, courseInfoVo);
        }
        courseInfoVo.setDescription(courseDesc.getDescription());
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int row = baseMapper.updateById(eduCourse);
        if (row > 0) {
            EduCourseDescription description = new EduCourseDescription();
            description.setId(courseInfoVo.getId());
            description.setDescription(courseInfoVo.getDescription());
            eduCourseDescriptionService.updateById(description);
        }
    }

    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        return eduCourseMapper.getPublishCourseInfo(id);
    }

    @Override
    public Map<String, Object> getCourseList(Long pageNo, Long pageSize, EduCourse eduCourse) {
        Page<EduCourse> page = new Page<>(pageNo, pageSize);
        QueryWrapper<EduCourse> qw = new QueryWrapper<>();
        qw.like(eduCourse.getTitle() != null, "title", eduCourse.getTitle())
                .like(eduCourse.getStatus() != null, "status", eduCourse.getStatus());
        IPage<EduCourse> eduCourseIPage = baseMapper.selectPage(page, qw);
        Map<String, Object> map = new HashMap<>();
        map.put("rows", eduCourseIPage.getRecords());
        map.put("total", eduCourseIPage.getTotal());
        return map;
    }

    @Override
    public void removeCourse(String courseId) {
        //根据课程id删除小节
        eduVideoService.removeVideoByCourseId(courseId);
        //根据课程id删除章节
        eduChapterService.removeChapterByCourseId(courseId);
        //根据课程id删除描述
        eduCourseDescriptionService.removeById(courseId);
        //根据课程id删除课程本身
        int res = baseMapper.deleteById(courseId);
        if (res == 0) {
            throw new ELeanExeception(20001, "删除失败");
        }
    }

    @Override
    public void changeStatus(String courseId) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(courseId);
        eduCourse.setStatus(CourseStatus.Normal.getValue());
        baseMapper.updateById(eduCourse);
    }

    @Cacheable(key = "'selectIndexData'", value = "course-teacher")
    @Override
    public Map<String, Object> buildIndexData() {
        List<EduCourse> eduCourses = selectCourses();
        List<EduTeacher> eduTeachers = selectTeacher();
        Map<String, Object> map = new HashMap<>();
        map.put("courseList", eduCourses);
        map.put("teacherList", eduTeachers);
        return map;
    }

    @Override
    public List<EduCourse> getCourseByTeacherId(String id) {
        QueryWrapper<EduCourse> qw = new QueryWrapper<>();
        qw.eq("teacher_id", id);
        return baseMapper.selectList(qw);
    }

    @Override
    public Map<String, Object> getFrontCourseList(long page, long limit, CourseFrontVo courseFrontVo) {
        Page<EduCourse> pageParam = new Page<>(page, limit);
        QueryWrapper<EduCourse> qw = new QueryWrapper<EduCourse>();
        //判断条件值是否为空，不为空拼接
        if (!StringUtils.isEmpty(courseFrontVo.getTitle())) {
            qw.like("title", courseFrontVo.getTitle());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) {
            qw.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) {
            qw.eq("subject_id", courseFrontVo.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {
            qw.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {
            qw.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {
            qw.orderByDesc("price");
        }
        baseMapper.selectPage(pageParam, qw);

        Map<String,Object> map = new HashMap<>();
        map.put("records",pageParam.getRecords());
        map.put("current",pageParam.getCurrent());
        map.put("pages",pageParam.getPages());
        map.put("size",pageParam.getSize());
        map.put("total",pageParam.getTotal());
        map.put("hasNext",pageParam.hasNext());
        map.put("hasPrevious",pageParam.hasPrevious());
        return map;
    }

    /**
     * 根据课程id获取课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.selectBaseCourseInfo(courseId);
    }

    /**
     * 查询8条课程信息
     *
     * @return
     */
    public List<EduCourse> selectCourses() {
        QueryWrapper<EduCourse> qw = new QueryWrapper<>();
        qw.orderByDesc("id")
                .last("limit 8");
        return baseMapper.selectList(qw);
    }

    /**
     * 查询4条名师信息
     *
     * @return
     */
    public List<EduTeacher> selectTeacher() {
        QueryWrapper<EduTeacher> qw = new QueryWrapper<>();
        qw.orderByDesc("id")
                .last("limit 4");
        return teacherService.list(qw);
    }

}
